import { getInfo, logout, smsLogin, cutLogin, bindStore } from "@/api/login";
import { getToken, removeToken, setToken } from "@/utils/auth";
import constant from "@/utils/constant";
import storage from "@/utils/storage";

import config from "../../../config";

const baseUrl = config.baseUrl;

const user = {
  state: {
    token: getToken(),
    wxUserId: storage.get(constant.wxUserId),
    userType: storage.get(constant.userType),
    wxUserName: storage.get(constant.wxUserName),
    wxAvatar: storage.get(constant.wxAvatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),

    storeStatus: storage.get(constant.storeStatus),
    entDataStatus: storage.get(constant.entDataStatus),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERTYPE: (state, userType) => {
      state.userType = userType;
    },
    SET_WXUSERID: (state, wxUserId) => {
      state.wxUserId = wxUserId;
    },
    SET_WXUSERNAME: (state, wxUserName) => {
      state.wxUserName = wxUserName;
      storage.set(constant.wxUserName, wxUserName);
    },
    SET_WXAvatar: (state, wxAvatar) => {
      state.wxAvatar = wxAvatar;
      storage.set(constant.wxAvatar, wxAvatar);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      storage.set(constant.roles, roles);
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
      storage.set(constant.permissions, permissions);
    },

    SET_storeStatus: (state, storeStatus) => {
      state.storeStatus = storeStatus;
      storage.set(constant.storeStatus, storeStatus);
    },
    SET_entDataStatus: (state, entDataStatus) => {
      state.entDataStatus = entDataStatus;
      storage.set(constant.entDataStatus, entDataStatus);
    },
  },

  actions: {
    // 短信登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        smsLogin(userInfo)
          .then((res) => {
            console.log(res, "登录");
            setToken(res.data.token);
            commit("SET_TOKEN", res.data.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            console.log(res, "---------获取用户信息");
            const user = res.data || null;
            const wxAvatar = baseUrl + user.wxAvatar || "";
            const userwxUserName = user.userwxUserName || "";
            const userType = user.currentLoginType || "";
            const wxUserId = user.wxUserId || "";
            // 是否关联门店状态
            const storeStatus = user.storeStatus || "";
            // 是否已完善企业资料状态
            const entDataStatus = user.entDataStatus || "";

            commit("SET_WXUSERID", wxUserId); // 用户id
            commit("SET_USERTYPE", userType); // 用户类型
            commit("SET_WXUSERNAME", userwxUserName); // 用户名称
            commit("SET_WXAvatar", wxAvatar); // 用户头像
            commit("SET_storeStatus", storeStatus); //关联门店状态
            commit("SET_entDataStatus", entDataStatus); //是否已完善企业资料状态
            if (user.storeStatus === "0") {
              uni.setStorageSync('loginStatus', 1)
              // 扫码进来的用户登录成功后的处理
              if (uni.getStorageSync('scanStatus') && JSON.parse(uni.getStorageSync('scanStatus')).isScan === 1) {
                // 自动绑定店铺
                bindStore({
                  type:JSON.parse(uni.getStorageSync('scanStatus')).type,
                  storeId: JSON.parse(uni.getStorageSync('scanStatus')).storeId,
                  phonenumber: JSON.parse(uni.getStorageSync('scanStatus')).phonenumber
                }).then((res) => {
                  if (res.code == 200) {
                    uni.switchTab({
                      url: "/pages/tabbarChange/firstPage/index",
                    });
                  }
                });
              } else {
                console.log('storeid', uni.getStorageSync('storeId'))
                if (uni.getStorageSync('storeId')) {
                  uni.switchTab({
                    url: "/pages/tabbarChange/firstPage/index",
                  });
                } else {
                  uni.navigateTo({
                    url: "/pages/recruit/login/selectStores/index",
                  });
                }
              }

            } else {
              console.log(4)
              uni.setStorageSync('loginStatus', 1)
              uni.switchTab({
                url: "/pages/tabbarChange/firstPage/index",
              });
              // uni.navigateBack({
              //     success: () => {
              //         delta: 2;
              //     },
              //     fail: () => {
              //         uni.switchTab({
              //             url: "/pages/tabbarChange/firstPage/index",
              //         });
              //     },
              // });
            }

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit }) {
      console.log("退出登录，’------");
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 切换登录
    CutLogin({ dispatch, commit }, type) {
      console.log(type, "触发切换登录--------🧠🧠🧠🧠🧠🧠🧠🧠");
      return new Promise((resolve, reject) => {
        cutLogin(type)
          .then((res) => {
            console.log(res, "切换登录");
            setToken(res.data.token);
            commit("SET_TOKEN", res.data.token);
            // 获取用户信息
            dispatch("GetInfo");
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
